<template>
  <div class="app-container">
    <el-form ref="dataForm" :model="dataForm" status-icon label-width="300px">
      <div v-for="(item, index) in dataForm" :key="index">
          <el-form-item :label="getLabel(item.keyName)" :prop="`[${index}].keyValue`" :rules="rules.keyValue">
            <el-input v-model="item.keyValue"></el-input>
        </el-form-item>
      </div>

      <el-form-item>
        <el-button @click="cancel">{{$t('Cancel')}}</el-button>
        <el-button type="primary" @click="update">{{$t('Confirm')}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { otherConfig, updateOtherConfig } from '@/api/config'
  export default {
    name: "other",
    data() {
      const validateKeyValue = (rule, value, callback) => {
        if (!value) {
          callback(new Error(this.$t('不能为空')))
        } else if(!/^-?\d+\.?\d{0,2}$/.test(value)){
          callback(new Error(this.$t('不能超过两位小数')))
        } else {
          callback()
        }
      }
      return {
        dataForm: [{
          keyName: 'litemall_integral',
          keyValue: undefined
        },{
          keyName: 'litemall_integral_amount',
          keyValue: undefined
        }],
        rules: {
          "keyValue": [
            { required: true, message: this.$t('值不能为空'), trigger: 'blur' },
            { validator: validateKeyValue, trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      init: function() {
        this.dataForm.forEach((item, index) => {
          otherConfig(item).then(response => {
            item.keyValue = response.data.data
          })
        })
      },
      getLabel (keyName) {
        if ('litemall_integral' == keyName) {
          return this.$t('用户积分系数配置')
        } else if ('litemall_integral_amount' == keyName) {
          return this.$t('用户积分抵扣金额配置')
        } 
      },
      cancel() {
        this.init()
      },
      update() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateOtherConfig(this.dataForm)
              .then(response => {
                this.$notify.success({
                  title: this.$t('Success!'),
                  message: this.$t('Success!')
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: this.$t('Failed'),
                  message: this.$t(response.data.errmsg)
                })
              })
          }
        })
        
      }
    }
  }
</script>

<style scoped>

</style>
